<template>
  <div :id="containerId"></div>
</template>

<script>
import Vue from 'vue'
let id = 1
export default {
  name: "echart",
  data(){
    return {
      containerId:`echart_${id++}`,
      watchers:[],
      unParentLoadWatcher:'',
      hasDeactivated : false,
    }
  },
  props:{
    option:Object,
  },
  computed:{
    theme(){
      return this.$store.getters.theme
    }
  },
  watch:{
    option:{
      handler(){
        this.resetOption()
      },
      deep:true
    }
  },
  methods:{
    initOtherWatchers(){
      this.watchers.push(this.$watch(()=>{
        return `${this.$store.state.business.isVMenuCollapse}_${this.$store.state.business.isSetFullScreen}`
      },()=>{
        setTimeout(()=>{
          if(!this._inactive){
            this.doMyDispose()
            this.createEChart()
          }
        },100)
      }))
      this.watchers.push(this.$watch(()=>{
        return this.theme
      },()=>{
        this.doMyDispose()
        this.createEChart()
      }))
    },
    doMyDispose(){
      this.myChart.dispose()
      this.watchers.forEach(unWatcherFn=>unWatcherFn())
    },
    initParent(){
      const parent = this.$parent
      if(!parent['_isReactiveMounted']){
        Vue.util.defineReactive(parent,'_isMounted',parent._isMounted)
        parent['_isReactiveMounted'] = true
      }
      this.unParentLoadWatcher = this.$watch(()=>{
        return this.$parent._isMounted
      },()=>{
        this.createEChart()
      })
    },
    createEChart(){
      this.myChart = this.echarts.init(document.getElementById(this.containerId), this.theme, {renderer: 'svg'});
      this.myChart.setOption(this.option)
      this.initOtherWatchers()
    },
    resetOption(){
      this.myChart && this.myChart.setOption(this.option)
    }
  },
  beforeDestroy() {
    this.doMyDispose()
    this.unParentLoadWatcher && this.unParentLoadWatcher()
  },
  deactivated() {
    this.hasDeactivated = true
    this.doMyDispose()
  },
  activated() {
    this.hasDeactivated && this.createEChart()
  },
  created() {
    this.initParent()
  }
}
</script>
